# coding: utf8

"""
解析url，传值调用处理函数工具
取request参数，设置到全局变量

用例:
url: http://localhost:8000/rm/para/monitorAction!initData.do?opeator=1&redis.IP=192.168.15.44&redis.Port=3306&jboss.IP=192.168.15.55&jboss.Port=80&market.IP=192.168.15.66&market.Port=66&entrustIP=192.168.15.77#

rm/para/monitorAction!initData.do
?opeator=1
&redis.IP=192.168.15.44
&redis.Port=3306
&jboss.IP=192.168.15.55
&jboss.Port=80
&market.IP=192.168.15.66
&market.Port=66
&entrustIP=192.168.15.77
#

使用 date=xx, market=xx 初始化 cmriskwhtie 得到对象
调用 cmriskwhite 的 getdata 方法


class cmriskrule(object):

    def __init__(self):
        user_id = ''
        stock_code = ''

class cmriskwhite(object):

    def __init__(self):
        date = None
        market = None
        rule = cmriskrule()

    def getdata(self):
        print date
        print market
        print rule
        return ''
"""


# from django.http import HttpResponse
from httpUtil import HttpResponse

def paradeal(request, module, action, method):

    """使用rul初始化为一个模块设值，并且调用url中指定的方法

    """


    print action
    # 动态导入模块
    mo = __import__('.'.join(['apps', module, action]), globals(), locals(),[action])
    # print type(mo), mo

    # 初始化模块的全局变量
    if request.method == 'POST':
        form = request.POST
    elif request.method == 'GET':
        form = request.GET

    aim_dict = transquerydict(form)
    set_value_with_dict(mo, aim_dict)
    # 设置httpUtil中request的值
    if hasattr(mo, 'request'):
        setattr(mo, 'request', request)


    # 调用方法
    fun = getattr(mo, method)
    if method == 'execute':
        return apply(fun)
    else:
        return HttpResponse(apply(fun))

   # return HttpResponse('hello !')

import types
def set_value_with_dict(module, valuedict):

    """从一个字典对象给模块设置全局变量


    """
    # print 'model', module
    # print 'valuedict', valuedict
    keys_in_model = [key for key in dir(module)
                     if key in valuedict.keys()
                     and (
                        type(getattr(module, key)) in
                            (types.InstanceType, str, types.NoneType, int,
                            types.DictType, types.ListType, types.TupleType,
                            types.UnicodeType)
                        or
                        type(getattr(module, key)) not in types.__dict__.values()
                    )
    ]
    # print 'keys_in_model', keys_in_model
    from datetime import date, datetime
    for key in keys_in_model:
        key_type = type(getattr(module, key))
        # print 'key_type', key_type
        # 字符变量等 (可以直接赋值的或者只需要类型转换的)
        if key_type is int:
            val = int(valuedict[key][0])
        elif key_type in (str ,types.NoneType,types.UnicodeType):
            val = valuedict[key][0]
            # print key, 'va----lue', val
        # 列表变量
        elif key_type is set:
            val = set(valuedict.get(key))
        elif key_type is list:
            val = valuedict.get(key)
        elif key_type is tuple:
            val = tuple(valuedict.get(key))
        elif key_type in (date, datetime):
            try:
                val = datetime.strptime(valuedict[key][0].split('.')[0], '%Y-%m-%d %H:%M:%S')
            except Exception, e:
                val = None
        # 实例对象等
        elif key_type is types.InstanceType or key_type not in types.__dict__.values():
            # print key + u'是实例对象'
            # print getattr(module, key)
            set_value_with_dict(getattr(module, key), valuedict.get(key))
            val = getattr(module, key)
        else:
            val = None
        setattr(module, key, val)
        # print 'set : ', model, key, val


def transquerydict(src_dict):

    """将django的querydict转成一般的字典


    """

    normal_keys = [key for key in src_dict.keys() if key.find('.') < 0]
    dot_keys = set([key.split('.')[0] for key in src_dict.keys() if key.find('.') > 0])

    # print 'normal_keys', normal_keys
    # print 'dot_keys', dot_keys

    aim_dict = dict()
    for key in normal_keys:
        aim_dict[key] = src_dict.getlist(key)

    for key in dot_keys:
        aim_dict[key] = dict()
        for secondary_key in [primary_key.split('.', 1)[1] for primary_key in src_dict.keys() if primary_key.startswith(key+'.')]:
            aim_dict[key][secondary_key] = src_dict.getlist('.'.join([key, secondary_key]))

    return aim_dict



if __name__ == '__main__':
    # paradeal(None, 'rm', 'cmRiskWhite', 'auto')
    print 1